//
//  SpeakViewController.m
//  HeartOfMeet
//
//  Created by qianfeng on 16/3/30.
//  Copyright © 2016年 千云锋. All rights reserved.
//
#define kCollectionView ((kScreenWidth-3)/4 + 1)
#import "SpeakViewController.h"
#import "HeaderCollectionReusableView.h"
#import "DiscoverCollectionViewCell.h"
#import "zhuboModel.h"
#import "tuijianZhuboModel.h"
#import "moreSpeakViewController.h"
#import "SpeakDetailViewController.h"
@interface SpeakViewController ()<UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (nonatomic,strong)UIScrollView *scrollView;
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray *recSpeakArray;
@property (nonatomic,strong) NSMutableArray *speakArray;
@end

@implementation SpeakViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _recSpeakArray = [[NSMutableArray alloc] init];
    _speakArray = [[NSMutableArray alloc] init];
    [self createScrollView];
    [self fatchData];
    // Do any additional setup after loading the view.
}
- (void)fatchData{
    if (![self fatchFormLocal]) {
        [self fatchFormNetwork];
    }
}

- (BOOL)fatchFormLocal{
    return NO;
}

- (void)fatchFormNetwork{
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleShrink];
    [MMProgressHUD showWithTitle:@"请稍后" status:@"Loading..."];

    if  ([[EGOCache globalCache] hasCacheForKey:@"Speak1"]) {
        
        id cachData = [[EGOCache globalCache] plistForKey:@"Speak1"];
        NSDictionary *dataDict = cachData[@"data"];
        NSArray *diantaiArray = dataDict[@"diantai"];
        for (NSDictionary *diantaiDict in diantaiArray) {
            tuijianZhuboModel *diantaiModel = [[tuijianZhuboModel alloc] initWithDictionary:diantaiDict error:nil];
            
            [_recSpeakArray addObject:diantaiModel];
        }
        [MMProgressHUD dismissWithSuccess:@"下载完成" title:@"ok"];
        [self addCollectionView];
    }else{
        [[NetDataEngine sharedInstance] requestDiscoverUrl:LEADERURL success:^(id respondObject) {
            
            //保存下载后的数据
            [[EGOCache globalCache] setPlist:respondObject forKey:@"Speak1"];
            
            NSDictionary *dataDict = respondObject[@"data"];
            NSArray *diantaiArray = dataDict[@"diantai"];
            for (NSDictionary *diantaiDict in diantaiArray) {
                tuijianZhuboModel *diantaiModel = [[tuijianZhuboModel alloc] initWithDictionary:diantaiDict error:nil];
                
                [_recSpeakArray addObject:diantaiModel];
            }
            
            [self addCollectionView];
            [MMProgressHUD dismissWithSuccess:@"下载完成" title:@"ok"];
        } failed:^(NSError *error) {
            NSLog(@"%@",error);
        }];

    }

    if  ([[EGOCache globalCache] hasCacheForKey:@"Speak2"]) {
        
        id cachData = [[EGOCache globalCache] plistForKey:@"Speak2"];
      
        NSArray *dataArray = cachData[@"data"];
        for (NSDictionary *diantaiDict in dataArray) {
            zhuboModel *diantaiModel = [[zhuboModel alloc] initWithDictionary:diantaiDict error:nil];
            
            [_speakArray addObject:diantaiModel];
        }
        
        [_collectionView reloadData];
    }else{
        NSString * str = [NSString stringWithFormat:SPEAKLISTURL,12];
        [[NetDataEngine sharedInstance] requestDiscoverUrl:str success:^(id respondObject) {
            if (respondObject) {
                
                //保存下载后的数据
                [[EGOCache globalCache] setPlist:respondObject forKey:@"Speak2"];
                
                NSArray *dataArray = respondObject[@"data"];
                for (NSDictionary *diantaiDict in dataArray) {
                    zhuboModel *diantaiModel = [[zhuboModel alloc] initWithDictionary:diantaiDict error:nil];
                    
                    [_speakArray addObject:diantaiModel];
                }
                
                [_collectionView reloadData];
                
            }
            
        } failed:^(NSError *error) {
            NSLog(@"%@",error);
        }];

    }
    
}


-(void)createScrollView{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 49 - 64)];
    _scrollView.backgroundColor = [UIColor blackColor];
    _scrollView.delegate = self;
    [self.view addSubview:_scrollView];
    _scrollView.contentSize = CGSizeMake(kScreenWidth, kScreenWidth * 300 / 500 + 60 + kCollectionView * 4 );
    NSLog(@"%f",kCollectionView * 4);
    _scrollView.bounces = NO;
    
    [self addImageView];
    
}
- (void)addImageView{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth * 300 / 500)];
    imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"zhuanti_img_%u.jpg",arc4random() % 4]];
    [_scrollView addSubview:imageView];
}

- (void)addCollectionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumInteritemSpacing = 1;
    layout.minimumLineSpacing = 1;
    layout.itemSize = CGSizeMake(kCollectionView - 1, kCollectionView - 1);
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, kScreenWidth * 300 / 500, kScreenWidth, _scrollView.contentSize.height - kScreenWidth * 300 / 500) collectionViewLayout:layout];
    _collectionView.bounces = NO;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_collectionView];
    [_collectionView registerNib:[UINib nibWithNibName:@"DiscoverCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"DiscoverCollectionViewCell"];
    [_collectionView registerClass:[HeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerOne"];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 4;
    }else{
        return 12;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    DiscoverCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DiscoverCollectionViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:20/255.0 green:20/255.0 blue:20/255.0 alpha:1.0];
    if (indexPath.section == 0) {
        tuijianZhuboModel *model = self.recSpeakArray[indexPath.item];
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:model.avatar] placeholderImage:[UIImage imageNamed: @"placehold_rec"]];
        cell.myLabel.text = model.nickname;
    }else{
        if ([self.speakArray count] == 0) {
            return nil;
        }
        

        zhuboModel *model = self.speakArray[indexPath.item];
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:model.avatar] placeholderImage:[UIImage imageNamed: @"placehold_rec"]];
        cell.myLabel.text = model.nickname;
    }
    cell.myImageView.layer.masksToBounds = YES;
    cell.myImageView.layer.cornerRadius = cell.myImageView.frame.size.height / 2;

    return cell;

}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.section == 0) {
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            HeaderCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerOne" forIndexPath:indexPath];
            header.backgroundColor = [UIColor blackColor];
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(8, 0, 150, 30)];
            label.textColor = [UIColor whiteColor];
            if (indexPath.section == 0) {
                label.text = @"心灵之音  推荐主播";
            }else{
                label.text = @"心灵之音  热门主播";
                UIButton *button  = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame = CGRectMake(kScreenWidth - 90, 0, 90, 30);
                [button setTitle:@"查看更多" forState:UIControlStateNormal];
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:15];
                [button addTarget:self action:@selector(onClick) forControlEvents:UIControlEventTouchUpInside];
                [header addSubview:button];
            }
//            label.textAlignment = NSTextAlignmentCenter;
            label.font = [UIFont systemFontOfSize:15];
            [header addSubview:label];

            return header;
        }else{
            return nil;
        }
        
//    }
//    return nil;
}

- (void)onClick{
    NSLog(@"进入更多主播");
    moreSpeakViewController *moreSpeak = [[moreSpeakViewController alloc] init];
    moreSpeak.title = @"全部主播";
    [self.navigationController pushViewController:moreSpeak animated:YES];
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(0, 30);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 1, 0);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        tuijianZhuboModel *model = _recSpeakArray[indexPath.item];
        SpeakDetailViewController *speakDetailVC = [[SpeakDetailViewController alloc] init];
        speakDetailVC.title = model.nickname;
        speakDetailVC.userId = model.userId;
        speakDetailVC.nickname = model.nickname;
        speakDetailVC.avatar = model.avatar;
        speakDetailVC.favnum = model.favnum;
        speakDetailVC.viewnum = model.viewnum;
        speakDetailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:speakDetailVC animated:YES];
    }else{
        zhuboModel *model = _speakArray[indexPath.item];
        SpeakDetailViewController *speakDetailVC = [[SpeakDetailViewController alloc] init];
        speakDetailVC.title = model.nickname;
        speakDetailVC.userId = model.userId;
        speakDetailVC.nickname = model.nickname;
        speakDetailVC.avatar = model.avatar;
        speakDetailVC.favnum = model.favnum;
        speakDetailVC.viewnum = model.viewnum;
        speakDetailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:speakDetailVC animated:YES];
    }
}

@end




















